package L614;

import java.util.List;

/**
 * @program: javase
 * @description: 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 * @author: luolidong
 * @create: 2021-06-14 09:55
 * @version: 1.0
 */
public class Demo1 {
    public int[][] generateMatrix(int n) {
        int[][] matrix=new int[n][n];
        int top=0,bottom=n-1;
        int left=0,right=n-1;
        int numCount=n*n;

        while (numCount>0){
//            从左向右
            for (int i = left; i <= right &&numCount>0 ; i++) {
                matrix[top][i]=numCount;
                numCount--;
            }
            top++;
            for (int i = top; i <=bottom&&numCount>0  ; i++) {
                matrix[i][right]=numCount;
                numCount--;

            }
            right--;
            for (int i = right; i >=left&&numCount>0 ; i--) {
                matrix[bottom][i]=numCount;
                numCount--;

            }
            bottom--;
            for (int i = bottom; i >=top&&numCount>0 ; i--) {
                matrix[i][left]=numCount;
                numCount--;

            }
            left++;
        }
        return matrix;
    }
    public static void main(String[] args) {
//        int[][] m={{1,2,3},{4,5,6},{7,8,9}};
        int[][] ints = new Demo1().generateMatrix(3);
        for(int[] i:ints){
            for(int a:i){
                System.out.print(a);
            }
            System.out.println();
        }
    }
}
